import React, { useState } from 'react';
import {
  Box, Typography, Button, Grid, Paper, IconButton, Table,
  TableHead, TableRow, TableCell, TableBody, Tooltip,
  Dialog, DialogTitle, DialogContent, DialogActions,
  TextField, Select, MenuItem, FormControl, InputLabel,
  ThemeProvider, CssBaseline, Divider  
} from '@mui/material';
import { Edit, Delete, Add, UploadFile  } from '@mui/icons-material';
import theme from "../themes/theme ";

// 数据源类型定义
type DataSource = {
  name: string;
  type: string;
  frequency: string;
  apiPath?: string;
  authType?: string;
  token?: string;
  username?: string;
  password?: string;
};

type DataAnalysis = {
  name: string;
  type: 'file' | 'manual';
  data?: string; // 用于手工录入的数据内容
  file?: File; // 用于上传文件的数据
};

export default function DataSourceManagerPage() {
  const [dataSources, setDataSources] = useState<DataSource[]>([
    { name: 'ERP 系统数据', type: 'API', frequency: '每天 1 次' },
    { name: '财务报表数据', type: '数据库', frequency: '每小时 1 次' },
    { name: '业务系统指标', type: 'API', frequency: '每 15 分钟' },
  ]);

  const [dialogOpen, setDialogOpen] = useState(false);
  const [editIndex, setEditIndex] = useState<number | null>(null);
  const [newSource, setNewSource] = useState<DataSource>({
    name: '', type: 'API', frequency: '', apiPath: '',
    authType: 'None', token: '', username: '', password: ''
  });

   const [dataAnalysis, setDataAnalysis] = useState<DataAnalysis[]>([]);
  const [analysisDialogOpen, setAnalysisDialogOpen] = useState(false);
  const [newAnalysis, setNewAnalysis] = useState<DataAnalysis>({
    name: '',
    type: 'file',
    data: '',
    file: undefined
  });

  const handleOpenDialog = (index: number | null = null) => {
    if (index !== null) {
      setNewSource(dataSources[index]);
      setEditIndex(index);
    } else {
      setNewSource({
        name: '', type: 'API', frequency: '', apiPath: '',
        authType: 'None', token: '', username: '', password: ''
      });
      setEditIndex(null);
    }
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditIndex(null);
  };

  const handleSave = () => {
    if (!newSource.name || !newSource.type || !newSource.frequency) return;

    if (editIndex !== null) {
      const updated = [...dataSources];
      updated[editIndex] = newSource;
      setDataSources(updated);
    } else {
      setDataSources(prev => [...prev, newSource]);
    }
    handleCloseDialog();
  };

  const handleChange = (field: keyof DataSource, value: string) => {
    setNewSource(prev => ({ ...prev, [field]: value }));
  };

  const handleDelete = (index: number) => {
    const updated = [...dataSources];
    updated.splice(index, 1);
    setDataSources(updated);
  };

  // 新建数据分析操作
  const handleOpenAnalysisDialog = (type: 'file' | 'manual') => {
    setNewAnalysis({
      name: '',
      type,
      data: type === 'manual' ? '' : undefined,
      file: type === 'file' ? undefined : undefined
    });
    setAnalysisDialogOpen(true);
  };

  const handleAnalysisSave = () => {
    setDataAnalysis(prev => [...prev, newAnalysis]);
    setAnalysisDialogOpen(false);
  };
   const handleCloseAnalysisDialog = () => {
    setNewAnalysis({ name: '', type: 'file', data: '', file: undefined });
    setAnalysisDialogOpen(false);
  };
  const handleManualDataChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setNewAnalysis(prev => ({ ...prev, data: e.target.value }));
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setNewAnalysis(prev => ({ ...prev, file: e.target.files[0] }));
    }
  };

  const samplePreviewData = [
    { id: 'KPI001', name: '客户满意度', value: 85, status: '已映射' },
    { id: 'KPI002', name: '员工流失率', value: 12, status: '未映射' },
  ];
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box p={3} sx={{ backgroundColor: '#0b1e34', color: '#E1E8ED', minHeight: '100vh' }}>
        <Typography variant="h5" sx={{ color: '#F8F8F8', mb: 2 }}>数据源管理</Typography>

        <Paper sx={{ p: 3, backgroundColor: '#132f4c' }}>
          <Grid container justifyContent="space-between" alignItems="center" mb={2}>
            <Grid item>
              <Typography variant="subtitle1" sx={{ color: '#4FC3F7' }}>已配置数据源</Typography>
            </Grid>
            <Grid item>
              <Button
                variant="contained"
                startIcon={<Add />}
                onClick={() => handleOpenDialog()}
                sx={{ color: '#fff', backgroundColor: '#1976d2', '&:hover': { backgroundColor: '#1565c0' } }}
              >
                新建数据源
              </Button>
            </Grid>
          </Grid>

          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ color: '#4FC3F7' }}>名称</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>类型</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>采集频率</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>API地址</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>认证方式</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {dataSources.map((ds, i) => (
                <TableRow key={i}>
                  <TableCell sx={{ color: '#fff' }}>{ds.name}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{ds.type}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{ds.frequency}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{ds.apiPath || '-'}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{ds.authType || '-'}</TableCell>
                  <TableCell>
                    <Tooltip title="编辑">
                      <IconButton onClick={() => handleOpenDialog(i)}><Edit sx={{ color: '#FDD835' }} /></IconButton>
                    </Tooltip>
                    <Tooltip title="删除">
                      <IconButton onClick={() => handleDelete(i)}><Delete sx={{ color: '#EF5350' }} /></IconButton>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Paper>
        {/**新建数据源dialog */}
        <Dialog open={dialogOpen} onClose={handleCloseDialog} fullWidth maxWidth="sm">
          <DialogTitle sx={{ backgroundColor: '#132f4c', color: '#fff' }}>{editIndex !== null ? '编辑数据源' : '新建数据源'}</DialogTitle>
          <DialogContent sx={{ backgroundColor: '#132f4c' }}>
            <TextField
              fullWidth label="数据源名称" value={newSource.name}
              onChange={e => handleChange('name', e.target.value)} sx={{ mt: 2 }}
              InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
            />
            <FormControl fullWidth sx={{ mt: 2 }}>
              <InputLabel sx={{ color: '#E1E8ED' }}>类型</InputLabel>
              <Select value={newSource.type} onChange={e => handleChange('type', e.target.value)} sx={{ color: '#fff' }}>
                <MenuItem value="API">API</MenuItem>
                <MenuItem value="数据库">数据库</MenuItem>
              </Select>
            </FormControl>
            <TextField
              fullWidth label="采集频率" value={newSource.frequency}
              onChange={e => handleChange('frequency', e.target.value)} sx={{ mt: 2 }}
              InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
            />
            {newSource.type === 'API' && (
              <>
                <TextField
                  fullWidth label="API 地址" value={newSource.apiPath}
                  onChange={e => handleChange('apiPath', e.target.value)} sx={{ mt: 2 }}
                  InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
                />
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel sx={{ color: '#E1E8ED' }}>认证方式</InputLabel>
                  <Select
                    value={newSource.authType} onChange={e => handleChange('authType', e.target.value)}
                    sx={{ color: '#fff' }}>
                    <MenuItem value="None">无</MenuItem>
                    <MenuItem value="Token">Token</MenuItem>
                    <MenuItem value="Basic">Basic Auth</MenuItem>
                  </Select>
                </FormControl>
                {newSource.authType === 'Token' && (
                  <TextField
                    fullWidth label="Token" value={newSource.token}
                    onChange={e => handleChange('token', e.target.value)} sx={{ mt: 2 }}
                    InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
                  />
                )}
                {newSource.authType === 'Basic' && (
                  <>
                    <TextField
                      fullWidth label="用户名" value={newSource.username}
                      onChange={e => handleChange('username', e.target.value)} sx={{ mt: 2 }}
                      InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
                    />
                    <TextField
                      fullWidth label="密码" type="password" value={newSource.password}
                      onChange={e => handleChange('password', e.target.value)} sx={{ mt: 2 }}
                      InputLabelProps={{ sx: { color: '#E1E8ED' } }} InputProps={{ sx: { color: '#fff' } }}
                    />
                  </>
                )}
              </>
            )}
          </DialogContent>
          <DialogActions sx={{ backgroundColor: '#132f4c' }}>
            <Button onClick={handleCloseDialog} sx={{ color: '#E1E8ED' }}>取消</Button>
            <Button onClick={handleSave} variant="contained">保存</Button>
          </DialogActions>
        </Dialog>


      {/* 基础数据分析部分 */}
        <Divider sx={{ my: 3, borderColor: '#4FC3F7' }} />
        <Typography variant="h6" sx={{ color: '#F8F8F8', mb: 2 }}>基础数据分析</Typography>

        <Button
          variant="contained"
          startIcon={<UploadFile /> }
          onClick={() => handleOpenAnalysisDialog('file')}
          sx={{ color: '#fff', backgroundColor: '#1976d2', '&:hover': { backgroundColor: '#1565c0' }, mr: 2 }}
        >
          上传文件
        </Button>
        <Button
          variant="contained"
          onClick={() => handleOpenAnalysisDialog('manual')}
          sx={{ color: '#fff', backgroundColor: '#1976d2', '&:hover': { backgroundColor: '#1565c0' } }}
        >
          手工录入
        </Button>

        {/* 基础数据分析列表 */}
        <Paper sx={{ p: 3, backgroundColor: '#132f4c', mt: 3 }}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell sx={{ color: '#4FC3F7' }}>分析名称</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>类型</TableCell>
                <TableCell sx={{ color: '#4FC3F7' }}>操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {dataAnalysis.map((da, i) => (
                <TableRow key={i}>
                  <TableCell sx={{ color: '#fff' }}>{da.name}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{da.type === 'file' ? '上传文件' : '手工录入'}</TableCell>
                  <TableCell>
                    <Tooltip title="删除">
                      <IconButton onClick={() => setDataAnalysis(prev => prev.filter((_, index) => index !== i))}>
                        <Delete sx={{ color: '#EF5350' }} />
                      </IconButton>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Paper>

         {/* 基础数据分析 Dialog */}
        <Dialog open={analysisDialogOpen} onClose={handleCloseAnalysisDialog} fullWidth maxWidth="sm">
          <DialogTitle sx={{ backgroundColor: '#132f4c', color: '#fff' }}>{newAnalysis.type === 'file' ? '上传文件' : '手工录入'}</DialogTitle>
          <DialogContent sx={{ backgroundColor: '#132f4c' }}>
            <TextField
              fullWidth
              label="分析名称"
              value={newAnalysis.name}
              onChange={e => setNewAnalysis(prev => ({ ...prev, name: e.target.value }))}
              sx={{ mt: 2 }}
              InputLabelProps={{ sx: { color: '#E1E8ED' } }}
              InputProps={{ sx: { color: '#fff' } }}
            />

            {newAnalysis.type === 'file' ? (
              <>
                <Button component="label" variant="outlined" sx={{ mt: 2, color: '#fff', borderColor: '#4FC3F7' }}>
                  选择文件
                  <input hidden type="file" onChange={handleFileChange} />
                </Button>
                {newAnalysis.file && (
                  <>
                    <Typography sx={{ mt: 1, color: '#E1E8ED' }}>已选择文件: {newAnalysis.file.name}</Typography>
                    <Button variant="contained" sx={{ mt: 2, backgroundColor: '#388e3c', color: '#fff' }}>上传</Button>

                    <Typography variant="subtitle1" sx={{ color: '#4FC3F7', mt: 3 }}>数据预览</Typography>
                    <Table size="small" sx={{ mt: 1 }}>
                      <TableHead>
                        <TableRow>
                          <TableCell sx={{ color: '#4FC3F7' }}>指标 ID</TableCell>
                          <TableCell sx={{ color: '#4FC3F7' }}>指标名称</TableCell>
                          <TableCell sx={{ color: '#4FC3F7' }}>数值</TableCell>
                          <TableCell sx={{ color: '#4FC3F7' }}>映射状态</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {samplePreviewData.map((row, i) => (
                          <TableRow key={i}>
                            <TableCell sx={{ color: '#fff' }}>{row.id}</TableCell>
                            <TableCell sx={{ color: '#fff' }}>{row.name}</TableCell>
                            <TableCell sx={{ color: '#fff' }}>{row.value}</TableCell>
                            <TableCell sx={{ color: '#fff' }}>{row.status}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </>
                )}
              </>
            )  : (
              <>
                <TextField
                  fullWidth
                  label="手工录入数据"
                  value={newAnalysis.data}
                  onChange={e => setNewAnalysis(prev => ({ ...prev, data: e.target.value }))}
                  sx={{ mt: 2 }}
                  InputLabelProps={{ sx: { color: '#E1E8ED' } }}
                  InputProps={{ sx: { color: '#fff' } }}
                />

                <Typography variant="subtitle1" sx={{ color: '#4FC3F7', mt: 3 }}>数据治理能力域</Typography>
                <TextField
                  fullWidth
                  label="数据质量得分 (0-100)"
                  type="number"
                  inputProps={{ min: 0, max: 100 }}
                  sx={{ mt: 2 }}
                  InputLabelProps={{ sx: { color: '#E1E8ED' } }}
                  InputProps={{ sx: { color: '#fff' } }}
                />
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel sx={{ color: '#E1E8ED' }}>数据标准化程度</InputLabel>
                  <Select value={''} onChange={() => {}} sx={{ color: '#fff' }}>
                    <MenuItem value="高">高</MenuItem>
                    <MenuItem value="中">中</MenuItem>
                    <MenuItem value="低">低</MenuItem>
                  </Select>
                </FormControl>

                <Typography variant="subtitle1" sx={{ color: '#4FC3F7', mt: 3 }}>技术架构能力域</Typography>
                <TextField
                  fullWidth
                  label="架构评分 (0-100)"
                  type="number"
                  inputProps={{ min: 0, max: 100 }}
                  sx={{ mt: 2 }}
                  InputLabelProps={{ sx: { color: '#E1E8ED' } }}
                  InputProps={{ sx: { color: '#fff' } }}
                />
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel sx={{ color: '#E1E8ED' }}>架构成熟度</InputLabel>
                  <Select value={''} onChange={() => {}} sx={{ color: '#fff' }}>
                    <MenuItem value="高">高</MenuItem>
                    <MenuItem value="中">中</MenuItem>
                    <MenuItem value="低">低</MenuItem>
                  </Select>
                </FormControl>
              </>
            )}

            {newAnalysis.file && (
              <Typography sx={{ mt: 1, color: '#E1E8ED' }}>已选择文件: {newAnalysis.file.name}</Typography>
            )}
          </DialogContent>
          <DialogActions sx={{ backgroundColor: '#132f4c' }}>
            <Button onClick={handleCloseAnalysisDialog} sx={{ color: '#E1E8ED' }}>取消</Button>
            <Button onClick={handleAnalysisSave} variant="contained">保存</Button>
          </DialogActions>
        </Dialog>     
      </Box>
    </ThemeProvider>
  );
}
